package com.megvii.koala.guard;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by linyue on 16/1/24.
 */
public class BoxSearcher
{
    private DatagramSocket socket;

    private BoxSearcherThread thread;

    private ExecutorService searchThreadPool;

    private BoxSearcherListener listener;

    public void start()
    {
        try
        {
            socket = new DatagramSocket();
            thread = new BoxSearcherThread();
            thread.start();
            searchThreadPool = Executors.newCachedThreadPool();
        }
        catch (SocketException e)
        {
            e.printStackTrace();
        }
    }

    public void search()
    {
        searchThreadPool.submit(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    InetAddress serverAddress = InetAddress.getByName("255.255.255.255");
                    byte[] data = "hello".getBytes();
                    DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress,
                            54321);
                    socket.send(packet);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

    public void release()
    {
        if (thread != null)
        {
            thread.interrupt();
            thread = null;
        }
        if (socket != null)
        {
            socket.close();
            socket = null;
        }
        if (searchThreadPool != null)
        {
            searchThreadPool.shutdownNow();
        }
    }

    public void setListener(BoxSearcherListener listener)
    {
        this.listener = listener;
    }

    public interface BoxSearcherListener
    {
        public void onNewBoxSearched(String token);
    }

    public class BoxSearcherThread extends Thread
    {
        public void run()
        {
            byte[] buffer = new byte[1024];
            final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            try
            {
                while (!interrupted())
                {
                    socket.receive(packet);
                    String token = new String(buffer, 0, packet.getLength());
                    if (listener != null)
                    {
                        //TODO
                        listener.onNewBoxSearched(token);
                    }
                }
            }
            catch (SocketException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}
